package cc.ufinity.networkdiagnose.app;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.telephony.TelephonyManager;
import android.util.Log;
import cc.ufinity.networkdiagnose.manager.DBManager;
import cc.ufinity.networkdiagnose.manager.FTPConfig;
import cc.ufinity.networkdiagnose.manager.FtpTestManager;
import cc.ufinity.networkdiagnose.manager.TelManager;

/**
 * 保存 发生异常数据的 日志
 * 
 * @author
 * 
 */
public class AppLogs {
	private Activity ctx;
	private String path;
	private String localPath;
	private String remotePath;
	public static String logData = "";
	private FtpTestManager fm;
	public static boolean isUpload = false;

	public AppLogs(Context context) {
		ctx = (Activity) context;
		isUpload = false;
		String model = android.os.Build.MODEL;
		String version = android.os.Build.VERSION.RELEASE;
		TelephonyManager tm = (TelephonyManager) context
				.getSystemService(Context.TELEPHONY_SERVICE);
		String id = tm.getSubscriberId();
		String info = "[机型： " + model + " 系统版本：" + version + " : " + id
				+ " ]+ 手机号: "+getTelNumber()+"\n";
		logData = info + logData;
		try {
			/*
			 * path =
			 * Environment.getExternalStorageDirectory().getAbsolutePath();
			 * localPath = path + "/NetworkDiagnose_LOG/"; remotePath = "/log/";
			 */

			path = ctx.getFilesDir().getParent();
			localPath = path + File.separator + "logs" + File.separator;
			remotePath = File.separator + "logs" + File.separator;

			File fileDir2 = new File(localPath);
			fileDir2.mkdir();

			SimpleDateFormat formatter = new SimpleDateFormat(
					"yyyyMMddHHmmssSSS");
			Date curDate = new Date(System.currentTimeMillis());
			String fileName = getTelNumber() + "_"+formatter.format(curDate) + ".log";
			// 创建文件
			File newxmlfile = new File(localPath + fileName);

			try {
				if (!newxmlfile.exists()) {
					newxmlfile.createNewFile();
				}
			} catch (IOException e) {
				Log.e("CreateLog", "创建log文件出错：", e);
			}

			FileWriter fw = null;
			BufferedWriter bw = null;

			// 写入文件
			try {

				fw = new FileWriter(newxmlfile, false);//
				// 创建FileWriter对象，用来写入字符流
				bw = new BufferedWriter(fw); // 将缓冲对文件的输出
				String myreadline = logData;
				bw.write(myreadline + "\n"); // 写入文件
				bw.newLine();
				bw.flush(); // 刷新该流的缓冲
				bw.close();
				fw.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				try {
					bw.close();
					fw.close();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
				}
			}
			if (GlobalApp.DEBUG) {
				System.out.println("日志信息：\n"+logData);
			} else {
				upload(fileName);
			}
		} catch (Exception e) {
		}
	}

	private String getTelNumber(){
    	TelManager telManager = new TelManager(ctx);
    	String phoneNumber = telManager.getPhoneNumber();
    	if (phoneNumber == null || phoneNumber.equals("")) {
		}
    	return phoneNumber;
    }
	
	// 文件上传
	private void upload(final String fileName) {
		new Thread() {
			public void run() {
				 
				try {
					DBManager db = new DBManager(ctx);
					final FTPConfig ftp = db.getFtp();
					db.release();
					if (ftp != null && ftp.userName != null
							&& ftp.userName.length() > 0) {
						fm = new FtpTestManager(localPath, remotePath, "");
						int port = ftp.port;
						if (fm.login(ftp.address, port, ftp.userName,
								ftp.password)) {
							File file;
							fm.setFileName(fileName);
							isUpload = true;
							fm.upload();
							file = new File(localPath + fileName);
							if (file.exists()) {
								file.delete();
							}
						}
					}
				} catch (Exception e) {
				} finally {
					fm.logout();
				}
			}
		}.start();
	}
}
